<template>
  <div class="chat-area">
    <el-scrollbar class="chat-messages" ref="scrollbarRef">
      <div v-if="chatMessages.length === 0" class="chat-msg_zero">
        <div class="zero_card">
          <div class="zero_left">
            <h1>{{ t("chat.chatSubtitle") }}</h1>
            <p>{{ t("chat.chatPlaceholder") }}</p>
            <p>{{ t("chat.chatExample") }}</p>
          </div>
          <div class="zero_right">
            <img src="../../assets/images/机器人数量icon.png" />
          </div>
        </div>
      </div>
      <div
        v-for="(message, index) in chatMessages"
        :key="index"
        :class="[ 'chat-message', message.role === 'assistant' ? 'ai' : 'user' ]"
      >
        <div class="message-container">
          <img class="message-avatar" :src="messageAvatar(message.role)" />
  
          <div class="message-content">{{ message.content }}
            <el-icon v-if="message.role==='assistant'&&abortController&& index===chatMessages.length-1" class="stop-button" @click="abortStream"><VideoPause/></el-icon>
          </div>
        
          <!-- 添加闪动光标
          <div v-if="message.role === 'assistant'" class="cursor-blink">|</div> -->

        </div>

      </div>

     
  
  
    </el-scrollbar>
 
    <div class="chat-input-area">
    
      <input
        class="inputarea"
        v-model="inputValue"
        placeholder="Enter 发送"
        @keydown.enter.prevent="handleSendMessage"
      />
      <div class="input-area-buttom">
        <el-button class="input-buttons-send" @click="handleSendMessage">
          {{ t("chat.chatSendButton") }}
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { VideoPause } from "@element-plus/icons-vue";
import { ref,  reactive } from "vue";
import { t } from "../../locales"; // 引入全局 i18n
import { ElMessage } from "element-plus";
const scrollbarRef = ref(null);
const chatMessages = ref<{ role: string; content: string }[]>([]);
const inputValue = ref("");
const abortController=ref<AbortController|null>(null)

// 根据发送者返回头像
const messageAvatar = (role: string) => {
  return role === "assistant" ? "https://xiaoandi-westlake.oss-cn-beijing.aliyuncs.com/logo.png" : "https://xiaoandi-westlake.oss-cn-beijing.aliyuncs.com/006wsNcRly1hq24bcdd3qj31oe2ilx6p.jpg";
};

// 调用 AI API 的函数
const callAiApi = async (userMessage: string) => {
  const apiKey = "bce-v3/ALTAK-mpmEA0UbCHXFOUohK8jju/207e2c82611d0ed260e8878d28d00fcdd99bb0b9";
  const base_url = "https://qianfan.baidubce.com/v2/chat/completions";

  if (!userMessage.trim()) return;  // 如果消息为空，则直接返回


  //创建abortController
  abortController.value=new AbortController();

  // 构造历史对话
  const messages = chatMessages.value.map(msg => ({
    role: msg.role, // 使用 user 或 assistant 角色
    content: msg.content
  }));



  const body = {
    model: "ernie-3.5-8k",
    messages: messages,
    stream: true,  // 开启流式返回
    stream_options: {
      include_usage: false  // 是否包含 token 使用信息，默认为 false
    }
  };



  try {
    const resp = await fetch(base_url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization':`Bearer ${apiKey}`,
      },
      body: JSON.stringify(body),
      signal:abortController.value.signal//signal递给fetch
    });

    // 检查响应是否成功
    if (!resp.ok) {
      const errorText = await resp.text();
      ElMessage.error(`AI 请求失败: ${resp.status} ${resp.statusText} ${errorText}`)
      console.error(`AI 请求失败: ${resp.status} ${resp.statusText}`, errorText);
      return;
    }

    // 预先添加空的AI消息对象（使用reactive确保响应式）
    const aiMessage = reactive({ role: "assistant", content: "" });
    chatMessages.value.push(aiMessage);
    scrollToBottom(); // 立即滚动到底部
if(resp.body){
  const reader = resp.body.getReader();
    const decoder = new TextDecoder();
    let buffer = '';
    let done = false;

    while (!done) {
      const { value, done: readerDone } = await reader.read();
      done = readerDone;
      if(abortController.value?.signal.aborted){
        console.log('流式请求终止')
        break
      }
      buffer = decoder.decode(value || new Uint8Array(), { stream: !done });
        if (buffer.startsWith('data: ')) {
          const jsonStr = buffer.slice(6).trim();
          if (jsonStr === '[DONE]') continue;

          try {
            const data = JSON.parse(jsonStr);
            const deltaContent = data.choices[0]?.delta?.content || '';
            if (deltaContent) {
              aiMessage.content += deltaContent; // 逐步更新内容
              scrollToBottom(); // 每次更新后滚动
            }
          } catch (error) {
            console.error('解析JSON失败:', error);
          }
        }
      
    }
}else{
  ElMessage.error('流式解析出错误')
}
   
  } catch (error) {
    console.error("AI 请求失败:", error);
  }finally{
    //请求完成或终止之后，重置abortController
    abortController.value=null
  }
};

// 滚动到底部

const scrollToBottom = () => {
    //@ts-ignore
    const scrollbar = scrollbarRef.value.$el.querySelector('.el-scrollbar__wrap');
    if (scrollbar) {
      scrollbar.scrollTop = scrollbar.scrollHeight;
    }
  
};
// 发送消息处理
const handleSendMessage = () => {
  const message = inputValue.value.trim();
  if (!message) return; // 如果输入为空，则不发送请求


  // 添加当前用户消息
  chatMessages.value.push({ role: "user", content: message});

  // 清空输入框
  inputValue.value = "";

  // 调用 AI API 获取回复
  callAiApi(message);
};
//终止流式请求
const abortStream=()=>{
  if(abortController.value){
   abortController.value.abort()
   ElMessage.info('流式请求已终止')
  }
}
</script>

<style scoped lang="scss">
.chat-area {
  padding: 20px;
  display: flex;
  box-sizing: border-box;
  flex-direction: column;
  width: 100%;
  height: 100%;
  background-color: rgb(255, 255, 255);
  box-shadow: 2px 0 2px 0 rgba(0, 0, 0, 5%);
  border-radius: 0 32px 32px 0;
  overflow-x: hidden;

  .chat-messages {
    flex-grow: 1;
    padding: 10px;
    box-sizing: border-box;

    .chat-msg_zero {
      width: 100%;
      display: flex;
      justify-content: center;

      .zero_card {
        display: flex !important;
        align-items: center;
        justify-content: space-between;
        width: 50%;
        background-color: rgb(249, 249, 249);

        border-radius: 2rem;
        padding: 2rem;

        .zero_left {
          display: inline-block;

          h1 {
            font-weight: 700;
            font-size: 1.5rem;
            margin-bottom: 1rem;
          }

          p {
            font-size: 1.2rem;
            color: #777;
            margin-bottom: 1rem;
          }
        }

        .zero_right {
          display: inline-block;
        }
      }
    }

    /* 用户消息样式 */
    .chat-message.user .message-content {
      font-size: 18px;
      background-color: #e9e6e6;
      /* 白底 */
      color: #000000;
      /* 黑字 */
      font-family: "Arial", sans-serif;
      /* 修改字体样式 */
    }

    .chat-message.ai .message-content {
      font-size: 18px;
      background-color: rgb(106, 132, 244);
      /* 蓝底 */
      color: rgb(245, 242, 242);
      /* 白字 */
      font-family: "Arial", sans-serif;
      position: relative;
      /* 修改字体样式 */
      .stop-button{
        color: #f50808;
      font-size: 32px;
    
   position: absolute;
   top:10px;
   right:-40px;
   animation:pulse 1s infinite;
   transition: font-size 0.3s ease;
  }
  @keyframes pulse {
    0%{
      font-size: 32px;
    }
    50%{
      font-size: 34px;
    }
    100%{
      font-size: 32px;
    }

  }

    }

    /* 头像样式 */
    .message-avatar {
      width: 40px;
      height: 40px;
      border-radius: 50%;
      margin-right: 10px;
      margin-bottom: 5px;
    }

    /* 消息容器样式 */
    .message-container {
      display: flex;
      flex-direction: column;
      align-items: flex-start;
    }

    .chat-message.user .message-container {
      align-items: flex-end;
    }

    .chat-message.ai .message-container {
      align-items: flex-start;
    }

    .message-content {
      display: inline-block;
      padding: 10px 15px;
      border-radius: 10px;
      max-width: 70%;
      /* 限制消息宽度，不超过容器的 70% */
      word-wrap: break-word;
      /* 长单词自动换行 */
      word-break: break-all;
      /* 如果一行太长则强制换行 */
      overflow-wrap: break-word;
      /* 确保文本换行 */
    }

    /* 闪动光标样式 */
    .cursor-blink {
      animation: blink 3s infinite;
      font-size: 18px;
      color: #fff;
      font-weight: 700;
    }

    @keyframes blink {
      0%{
        opacity: 0;
      }
      50% {
        opacity: 1;
      }
      100%{
        opacity: 0;
      }
    }
  }

  .chat-input-area {
    display: flex;
    flex-direction: column;
    border: 2px solid skyblue;
    padding: 10px;
    margin: 5px;
    background-color: #fff;
    border-radius: 20px;
    box-shadow: 0 -1px 3px rgba(0, 0, 0, 0.1);
    margin-top: 10px;

    .inputarea {
      border: none;
      outline: none;
      /* 去掉焦点时的轮廓 */
      height: 40px;
      /* 设置高度为两行 */
      line-height: 20px;
      /* 每行的高度 */
      font-size: 16px;
      /* 设置字体大小 */
    }

    .input-buttons-send {
      margin-left: 10px;
      padding: 8px 12px;
      background-color: rgb(26, 161, 239);
      color: white;
      border: none;
      border-radius: 12px;
      cursor: pointer;
      width: 4rem;
      height: 2rem;
    }

    .input-area-buttom {
      display: flex;
      justify-content: end;
    }
  }
  

}
</style>